//
//  XFAccessModelView.swift
//  SinaBlog
//
//  Created by macs on 15/11/10.
//  Copyright © 2015年 BlackTail. All rights reserved.
//

import UIKit
import AFNetworking
class AccessViewModel: NSObject {
    //定义属性 access, 用来存放模型
    var access : UserAccess?
    //定义access_token,可以随时使用
    var access_token : String? {
        return access?.access_token
    }
    //定义属性用来记录用户的登录状态 true表示登录
    var userLogin : Bool {
        return access?.access_token != nil
    }
    
    var name : String? {
        return access?.name
    }
    
    var avatarUrl : NSURL? {
        return NSURL(string: (access?.avatar_large)!)
    }
    
    //在 init 方法中解档获得本地用户数据
    override init() {
        super.init()
        access = UserAccess.loadAccess()
    }
    
    func getAccess_token(code: String , finish : (error: NSError?)->()){
        
        let urlString = "oauth2/access_token"
        let parameters = ["client_id":client_id, "client_secret":client_secret, "grant_type":"authorization_code", "code":code, "redirect_uri":redirect_uri]
        
        Networktools.shareTools.requestJsonDict(HTTPType.POST, urlSting: urlString, parameters: parameters) { (result, error) -> () in
            
            if error != nil {
                
                print(error)
                return
            }
            //字典转模型
            let access = UserAccess(dict : result!)
            
            self.getUserInfo(access ,finish: finish)
            return
            
            
        }
        
    }
    
    func getUserInfo(access : UserAccess , finish : (error: NSError?)->()){
        
        let urlString = "2/users/show.json"
        let parameters = ["access_token":access.access_token!,"uid":access.uid!]
        
        Networktools.shareTools.requestJsonDict(HTTPType.GET, urlSting: urlString, parameters: parameters) { (result, error) -> () in
            
            if error != nil {
                finish(error: error)
                return
            }
            
            //字典转模型.获取用户信息 头像,昵称
            access.avatar_large = result!["avatar_large"] as? String
            access.name = result!["name"] as? String
            //print(access.name)
            //对数据进行归档操作
            access.savAccess()
            finish(error: nil)
        }
        
        
    }
    
}
